<template>
  <view class="container">
    <!-- 固定区域 -->
    <view class="fixed-header">
      <!-- 搜索栏 -->
      <view class="search-box">
        <uni-search-bar
          v-model="keyword"
          placeholder="搜索商品"
          :show-action="false"
          @confirm="handleSearchClick"
          @click="handleSearchClick"
        ></uni-search-bar>
      </view>

      <!-- 导航栏 -->
      <view class="nav-bar">
        <view 
          v-for="(item, index) in navItems" 
          :key="index"
          class="nav-item"
          :class="{ active: currentNav === item.type }"
          @click="switchNav(item.type)"
        >
          <image 
            :src="item.icon" 
            class="nav-icon"
            mode="aspectFit"
          />
          <text class="nav-text">{{ item.text }}</text>
          <view class="nav-line" v-if="currentNav === item.type"></view>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-area">
      <!-- 瀑布流展示商品 -->
      <waterfall-flow 
        v-if="displayProducts.length > 0"
        :products="displayProducts"
        @item-click="toProductDetail"
      ></waterfall-flow>

      <!-- 空状态 -->
      <view v-else class="empty-state">
        <text class="empty-text">暂无商品</text>
      </view>
    </view>

  </view>
</template>

<script>
import { checkLogin } from '@/utils/auth'
import api from '@/config/api'
import { mapUviewIconName } from '@/utils/icon-mapper.js'
import WaterfallFlow from '@/components/common/WaterfallFlow.vue'

export default {
  components: {
    WaterfallFlow
  },
  data() {
    return {
      keyword: '',
      navItems: [
        { 
          type: 'recommend', 
          text: '推荐',
          icon: '/static/icons/recommend.png'
        },
        { 
          type: 'hot', 
          text: '热销',
          icon: '/static/icons/hot.png'
        },
        { 
          type: 'new', 
          text: '新品',
          icon: '/static/icons/new.png'
        }
      ],
      currentNav: 'recommend',
      recommendProducts: [],
      hotProducts: [],
      newProducts: [],
      pageEnterTime: 0 // 记录进入页面的时间
    }
  },
  computed: {
    displayProducts() {
      switch (this.currentNav) {
        case 'recommend':
          return this.recommendProducts
        case 'hot':
          return this.hotProducts
        case 'new':
          return this.newProducts
        default:
          return []
      }
    }
  },
  onShow() {
    this.initData()
  },
  onHide() {
    // 不再需要记录首页停留时长
  },
  methods: {
    async initData() {
      try {
        const isLoggedIn = checkLogin()
        // 加载当前选中类型的商品
        await this.loadProductsByType(this.currentNav)
      } catch (error) {
        console.error('加载首页数据失败:', error)
      }
    },
    async switchNav(type) {
      if (this.currentNav === type) return
      this.currentNav = type
      await this.loadProductsByType(type)
    },
    async loadProductsByType(type) {
      try {
        const params = {
          pageNum: 1,
          pageSize: 30
        }

        switch (type) {
          case 'recommend':
            if (checkLogin()) {
              await this.loadPersonalizedRecommendations()
            } else {
              params.isRecommend = true
              await this.loadProducts(params)
            }
            break
          case 'hot':
            params.isHot = true
            await this.loadProducts(params)
            break
          case 'new':
            params.isNew = true
            await this.loadProducts(params)
            break
        }
      } catch (error) {
        console.error(`加载${type}类型商品失败:`, error)
      }
    },
    async loadProducts(params) {
      try {
        const res = await this.$api.product.base.list(params)
        if (res.code === 200 && res.data) {
          const products = res.data.records.map(item => ({
            id: item.id,
            name: item.name,
            subtitle: item.subtitle,
            price: item.price,
            originalPrice: item.originalPrice,
            mainImage: item.mainImage,
            subImages: item.subImages ? item.subImages.split(',') : [],
            sales: item.sales,
            stock: item.stock,
            isHot: item.isHot,
            isNew: item.isNew,
            isRecommend: item.isRecommend,
            viewCount: item.viewCount,
            favoriteCount: item.favoriteCount,
            ratingAvg: item.ratingAvg,
            reviewCount: item.reviewCount
          }))

          // 根据当前导航类型更新对应的商品数组
          switch (this.currentNav) {
            case 'recommend':
              this.recommendProducts = products
              break
            case 'hot':
              this.hotProducts = products
              break
            case 'new':
              this.newProducts = products
              break
          }
        }
      } catch (error) {
        console.error('加载商品列表失败:', error)
        // 清空对应类型的商品数组
        switch (this.currentNav) {
          case 'recommend':
            this.recommendProducts = []
            break
          case 'hot':
            this.hotProducts = []
            break
          case 'new':
            this.newProducts = []
            break
        }
      }
    },
    handleSearchClick() {
      // 点击搜索框时直接跳转到搜索页面
      uni.navigateTo({
        url: '/pages/product/search/index'
      })
    },
    toProductDetail(product) {
      const id = product.id || product.productId
      if (!id) return
      
      // 直接跳转到商品详情页，不再记录点击行为
      uni.navigateTo({
        url: `/pages/product/detail/index?id=${id}`
      })
    },
    async loadPersonalizedRecommendations() {
      try {
        const res = await this.$api.product.recommendation.getPersonalized(30)
        if (res.code === 200 && res.data) {
          this.recommendProducts = res.data.map(item => ({
            id: item.id,
            name: item.name,
            subtitle: item.subtitle,
            price: item.price,
            originalPrice: item.originalPrice,
            mainImage: item.mainImage,
            subImages: Array.isArray(item.subImages) ? item.subImages : (item.subImages ? item.subImages.split(',') : []),
            sales: item.sales,
            stock: item.stock,
            isHot: item.isHot === 1,
            isNew: item.isNew === 1,
            isRecommend: item.isRecommend === 1,
            viewCount: item.viewCount,
            favoriteCount: item.favoriteCount,
            ratingAvg: item.ratingAvg,
            reviewCount: item.reviewCount
          }))
        }
      } catch (error) {
        console.error('加载个性化推荐失败:', error)
        this.recommendProducts = []
      }
    },
    async recordBehavior(productId = null, stayDuration = 0) {
      // 移除此方法，不再需要
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.search-box {
  margin-bottom: 20rpx;
  
  :deep(.uni-searchbar) {
    padding: 0;
    background-color: transparent;
    
    .uni-searchbar__box {
      height: 72rpx;
      border-radius: 36rpx;
      background-color: #f7f7f7;
      border: none;
      
      .uni-searchbar__text-input {
        font-size: 28rpx;
        color: #333;
      }
    }
  }
}

.nav-bar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 88rpx;
  position: relative;
  
  .nav-item {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0 20rpx;
    
    .nav-icon {
      width: 44rpx;
      height: 44rpx;
      margin-bottom: 6rpx;
    }
    
    .nav-text {
      font-size: 28rpx;
      color: #666;
      transition: color 0.3s;
    }
    
    .nav-line {
      position: absolute;
      bottom: -16rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 40rpx;
      height: 4rpx;
      background: $uni-primary;
      border-radius: 2rpx;
    }
    
    &.active {
      .nav-text {
        color: $uni-primary;
        font-weight: 500;
      }
    }
  }
}

.content-area {
  margin-top: 200rpx;
  padding: 20rpx;
}

:deep(.waterfall-flow) {
  .product-item {
    background: #fff;
    border-radius: 16rpx;
    overflow: hidden;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
    transition: transform 0.3s;
    
    &:active {
      transform: scale(0.98);
    }
    
    .product-image {
      width: 100%;
      border-radius: 16rpx 16rpx 0 0;
    }
    
    .product-info {
      padding: 20rpx;
      
      .product-name {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        @include text-ellipsis(2);
        margin-bottom: 10rpx;
      }
      
      .product-subtitle {
        font-size: 24rpx;
        color: #999;
        @include text-ellipsis;
        margin-bottom: 16rpx;
      }
      
      .price-section {
        display: flex;
        align-items: baseline;
        
        .price {
          font-size: 32rpx;
          color: $uni-primary;
          font-weight: bold;
          
          &::before {
            content: '¥';
            font-size: 24rpx;
            margin-right: 4rpx;
          }
        }
        
        .original-price {
          font-size: 24rpx;
          color: #999;
          text-decoration: line-through;
          margin-left: 12rpx;
          
          &::before {
            content: '¥';
            font-size: 20rpx;
          }
        }
      }
      
      .stats {
        display: flex;
        align-items: center;
        margin-top: 12rpx;
        font-size: 22rpx;
        color: #999;
        
        .stat-item {
          margin-right: 16rpx;
          display: flex;
          align-items: center;
          
          .icon {
            font-size: 24rpx;
            margin-right: 4rpx;
          }
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-top: 20rpx;
  }
}
</style>